package com.prodavalnik.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.prodavalnik.model.DataBaseController;


/**
 * Servlet implementation class LikeServlet
 */
@WebServlet("/LikeServlet")
public class LikeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LikeServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		HttpSession session = request.getSession();
		PrintWriter pw = response.getWriter();
		String prId = request.getParameter("prid");
		int productId = Integer.parseInt(prId);
		
		if(session == null){
			pw.write("false");
			return;
		}
		
		String username = (String) session.getAttribute("username");

		
		if(username.equals("")){
			pw.write("false");
			return;
		}
			int userID = 0;
			int categoryID = 0;
			try {
				userID = DataBaseController.getUserId(username);
				categoryID = DataBaseController.getCategoryIdByProductId(productId);
			} catch (SQLException e) {
				pw.write("false");
				return;
			}
		
			DataBaseController.addRecordToUserLikedCategories(userID,categoryID);
		
			pw.write("true");
	}

}
